package com.duomi88.nettybio;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;

/**
 * 服务端通讯消息处理。
 * 公众号 duomi88
 */
public class Receiver implements ChannelInboundHandler{
	
	
	private static Logger LOG  = Logger.getLogger(NettyClient.class);
	//请求阻塞池，key为sn
	private static Map<String,CountDownLatch> waitLatch = new HashMap<String, CountDownLatch>();
	
	//返回消息池，key为sn
	private static Map<String,String> response = new HashMap<String, String>();
	
	public static void addWait(String sn) {
		waitLatch.put(sn, new CountDownLatch(1));
	}
	public static void block(String sn) throws InterruptedException {
		waitLatch.get(sn).await();
	}
	public static String  getResponse(String sn) {
		return  response.get(sn);
	}
	/**
	 * 处理服务端返回消息
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			String dataFromServer = (String) msg;
			String[] snData = dataFromServer.split("@");
			String sn = snData[0];
			String data = snData[1];
			response.put(sn, data);//等待业务逻辑消费
			if(!waitLatch.containsKey(sn)) {
				LOG.error("非法sn："+sn);
				return;
			}
			waitLatch.get(sn).countDown();//取消阻塞，让发送线程后续逻辑运行。
			waitLatch.remove(sn);
		} catch (Exception e) {
			LOG.error("接收到非法数据:"+msg);
		}
	}
	/**
	 * 建立连接
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		String serverIp = ((InetSocketAddress)ctx.channel().remoteAddress()).getHostString();
		LOG.info("与服务端["+serverIp+"]建立连接");
	}

	/**
	 * 连接断开
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		String serverIp = ((InetSocketAddress)ctx.channel().remoteAddress()).getHostString();
		LOG.warn("与服务端["+serverIp+"]连接断开");
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {}
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {}
	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {}
	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {}
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {}
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {}
	@Override
	public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {}

}